//
//  VBaseViewController.m
//  BuaatVolunteerSDK
//
//  Created by vincent luo on 15/6/11.
//  Copyright (c) 2015年 vincent luo. All rights reserved.
//

#import "VBaseViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "AFHTTPRequestOperation.h"
#import "AFNetworking.h"

#import <CoreLocation/CoreLocation.h>

#import "BuaatVolunteerSDK.h"
#import "BuaatManager.h"

#define apiHost   @""

#define SDKVersion     @"1.0.0"

@interface VBaseViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;

@property (nonatomic,strong) NSString *longitude;
@property (nonatomic,strong) NSString *latitude;
@end

@implementation VBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [BuaatManager sharedInstance].sdkVersion = SDKVersion;
    
    //判断是否已经发送，如果发送了，就不再获取地址位置
    if (![BuaatManager sharedInstance].isSend) {
        [self getLocation];
        //        [self senderBaseInfo];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    
}


#pragma mark 发送基本信息
-(void)senderBaseInfo
{
    if (![BuaatManager sharedInstance].isSend) {
        
        [BuaatManager sharedInstance].isSend = YES;
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        NSDictionary *parameters = [self getBaseInfo];
        
        
        [manager POST:apiHost parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = responseObject;
            if ([dic isKindOfClass:[NSDictionary class]]||[dic isKindOfClass:[NSArray class]]) {
                [BuaatManager sharedInstance].isSend = YES;
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [BuaatManager sharedInstance].isSend = NO;
            
        }];
    }
    
    
}

#pragma mark 获取地理位置
-(void)getLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];
        
        
        
    }else
    {
        
    }
}

#pragma mark 获取经纬度
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    
    self.longitude = [NSString stringWithFormat:@"%f",coor.longitude];
    self.latitude = [NSString stringWithFormat:@"%f",coor.latitude];
    [self.locationManager stopUpdatingLocation];
    [self senderBaseInfo];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [self senderBaseInfo];
}
-(NSDictionary *)getBaseInfo{
    
    //app应用相关信息的获取
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    // CFShow(dicInfo);
    
    NSString *strAppName = [dicInfo objectForKey:@"CFBundleDisplayName"];
    //    NSLog(@"App应用名称：%@", strAppName);   // 当前应用名称
    if (!strAppName) {
        strAppName = @"";
    }
    
    
    NSString *strAppVersion = [dicInfo objectForKey:@"CFBundleShortVersionString"];
    //    NSLog(@"App应用版本：%@", strAppVersion);    // 当前应用软件版本  比如：1.0.1
    
    
    NSString *carrier = [self setupCarrier];
    //    NSLog(@"运营商 = %@",[self setupCarrier]);
    
    NSString *usedSpace = [self usedSpaceAndfreeSpace];
    
    NSString *unusedSpace = [self leaveSpace];
    
    NSString *systemPlaform = @"iOS";//系统平台
    
    NSString *strSysVersion = [[UIDevice currentDevice] systemVersion];
    //    NSLog(@"系统版本号：%@", strSysVersion);// e.g. @"4.0"
    
    NSString* phoneModel = [[UIDevice currentDevice] model];
    //    NSLog(@"手机型号: %@",phoneModel );   //手机型号
    
    NSString *netState =[self networkingStatesFromStatebar];
    //    NSLog(@"网络状态 = %@",);
    
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    NSString *elePower =[NSString stringWithFormat:@"%0.0f",[[UIDevice currentDevice] batteryLevel]*100];
    //    NSLog(@"电量 = %f", [[UIDevice currentDevice] batteryLevel]);
    
    NSString *mobLanguage = [self getLanuage];
    
    NSString *mobCountry = [self getCountry];
    
    //    NSLog(@"国家：%@", country); //en_US
    
    NSString *timeZone = [NSString stringWithFormat:@"%@",[NSTimeZone localTimeZone]];
    
    //ip地址
    NSString *ipAddress = [self getIPAddress];
    
    NSString *longitude = @"未知";
    if (self.longitude) {
        longitude = self.longitude;
    }
    
    
    NSString *latitude = @"未知";
    if (self.latitude) {
        latitude = self.latitude;
    }
    
    
    NSDictionary *returnDic = @{@"appName":strAppName,
                                @"appVersion":strAppVersion,
                                @"telCarrier":carrier,
                                @"usedRom":usedSpace,
                                @"unusedRom":unusedSpace,
                                @"systemPlatform":systemPlaform,
                                @"systemVersion":strSysVersion,
                                @"telModel":phoneModel,
                                @"netState":netState,
                                @"elePower":elePower,
                                @"mobLanguage":mobLanguage,
                                @"mobCountry":mobCountry,
                                @"timeZone":timeZone,
                                @"ipAddress":ipAddress,
                                @"publicIpAddress":@"",
                                @"longitude":longitude,
                                @"latitude":latitude};
    NSLog(@"returnDic = %@",returnDic);
    
    //存储空间
    //    [self usedSpaceAndfreeSpace];
    
    //    NSLog(@"uuid = %@", [self generateUuidString]);
    
    
    return returnDic;
    
}

#pragma mark 获取国家
-(NSString *)getCountry
{
    //    zh-CN 简体中文，中华人民共和国
    //    zh-HK 繁体中文，香港特别行政区
    //    zh-MO 繁体中文，澳门特别行政区
    //    zh-SG 繁体中文，新加坡
    //    zh-TW 繁体中文，台湾
    //    NSLog(@"语言：%@", language);//en
    
    
    NSLocale *locale = [NSLocale currentLocale];
    NSString *mobCountryStr = [locale localeIdentifier];
    NSArray *arr = [mobCountryStr componentsSeparatedByString:@"_"];
    NSString *mobCountry = [arr lastObject];
    
    if ([mobCountry isEqualToString:@"CN"]) {
        return @"中国大陆";
    }
    if ([mobCountry isEqualToString:@"HK"]) {
        return @"中国香港";
    }
    if ([mobCountry isEqualToString:@"MO"]) {
        return @"中国澳门";
    }
    if ([mobCountry isEqualToString:@"TW"]) {
        return @"中国台湾";
    }
    
    return mobCountry;
}
#pragma mark 获取语言
-(NSString *)getLanuage
{
    NSArray *languageArray = [NSLocale preferredLanguages];
    //
    NSString *mobLanguage = [languageArray objectAtIndex:0];
    
    //zh-Hans  简体中文
    //zh-Hant  繁体中文
    
    if ([mobLanguage isEqualToString:@"zh-Hans"]) {
        mobLanguage = @"简体中文";
    }
    
    if ([mobLanguage isEqualToString:@"zh-Hant"]) {
        mobLanguage = @"繁体中文";
    }
    //    if (<#condition#>) {
    //        <#statements#>
    //    }
    
    
    return mobLanguage;
}
#pragma mark 运营商
-(NSString *)setupCarrier
{
    NSString *carrierStr = @"";
    CTTelephonyNetworkInfo *netInfo =[[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier =[netInfo subscriberCellularProvider];
    if (carrier == nil)
    {
        carrierStr = @"";
    }
    else
    {
        NSString *mcc =[carrier mobileCountryCode];
        NSString *mnc =[carrier mobileNetworkCode];
        carrierStr = [mcc stringByAppendingString:mnc];
    }
    
    
    //    46001中国联通
    //    46002中国移动
    //    46003中国电信
    //    46007中国移动
    NSString *returnStr = @"其他";
    if ([carrierStr isEqualToString:@"46001"]) {
        returnStr = @"中国联通";
    }
    
    if ([carrierStr isEqualToString:@"46002"]||[carrierStr isEqualToString:@"46007"]) {
        returnStr = @"中国移动";
    }
    
    if ([carrierStr isEqualToString:@"46003"]) {
        returnStr = @"中国电信";
    }
    
    return returnStr;
}



#pragma mark 已占用
-(NSString *)usedSpaceAndfreeSpace{
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] ;
    NSFileManager* fileManager = [[NSFileManager alloc ]init];
    NSDictionary *fileSysAttributes = [fileManager attributesOfFileSystemForPath:path error:nil];
    NSNumber *freeSpace = [fileSysAttributes objectForKey:NSFileSystemFreeSize];
    NSNumber *totalSpace = [fileSysAttributes objectForKey:NSFileSystemSize];
    NSString  * str= [NSString stringWithFormat:@"%0.0fM",([totalSpace longLongValue] - [freeSpace longLongValue])/1024.0/1024.0];
    return str;
}
#pragma mark 剩余
-(NSString *)leaveSpace
{
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] ;
    NSFileManager* fileManager = [[NSFileManager alloc ]init];
    NSDictionary *fileSysAttributes = [fileManager attributesOfFileSystemForPath:path error:nil];
    NSNumber *freeSpace = [fileSysAttributes objectForKey:NSFileSystemFreeSize];
    NSString  * str= [NSString stringWithFormat:@"%0.0fM",[freeSpace longLongValue]/1024.0/1024.0];
    return str;
}

- (NSString *)networkingStatesFromStatebar {
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    
    NSString *stateString = @"wifi";
    
    switch (type) {
        case 0:
            stateString = @"无网络";
            break;
            
        case 1:
            stateString = @"2G";
            break;
            
        case 2:
            stateString = @"3G";
            break;
            
        case 3:
            stateString = @"4G";
            break;
            
        case 4:
            stateString = @"LTE";
            break;
            
        case 5:
            stateString = @"WIFI";
            break;
            
        default:
            break;
    }
    
    return stateString;
}

- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}


- (void)getLANIPAddressWithCompletion:(void (^)(NSString *IPAddress))completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *IP = [self getIPAddress];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(IP);
            }
        });
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
